package nacos

import (
	"dmsv/etc"
	"github.com/beego/beego/v2/core/logs"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"os"
)

const (
	gDataId = "config"
)

func configInit(nameSpaceId, addr string, port uint64) error {

	// create ServerConfig
	sc := []constant.ServerConfig{
		*constant.NewServerConfig(
			addr,
			port,
			constant.WithScheme("http"),
			constant.WithContextPath("/nacos")),
	}

	cc := constant.ClientConfig{
		NamespaceId:         nameSpaceId, //namespace id
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "logs/nacos",
		CacheDir:            "logs/nacos/cache",
		RotateTime:          "1h",
		MaxAge:              3,
		LogLevel:            "debug",
	}

	// a more graceful way to create config client
	client, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)

	if err != nil {
		return (err)
	}

	//get config
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: gDataId,
		Group:  gRunMode,
	})

	//logs.Debug("获取配置:\n%v", content)
	err = etc.InitConfigFromData([]byte(content))
	if err != nil {
		logs.Error("配置解析失败:%v", err)
		os.Exit(1)
	} else {
		logs.Debug("配置解析成功")
	}

	//Listen config change,key=dataId+group+namespaceId.
	err = client.ListenConfig(vo.ConfigParam{
		DataId: gDataId,
		Group:  gRunMode,
		OnChange: func(namespace, group, dataId, data string) {
			logs.Debug("配置修改:config changed group:" + group + ", dataId:" + dataId + ", content:" + data)
			etc.UpdateConfigFromData([]byte(data))
		},
	})

	if err != nil {
		logs.Error("监听配置失败....")
	} else {
		logs.Debug("监听配置成功....")
	}
	return nil
}
